import { Image } from 'antd';
import { useEffect, useRef } from 'react';
import * as THREE from 'three';
import './TargetDetection.css';
const TargetDetection = (props: {
  src: string;
  sel?: any;
  allRect?: any;
  data?: {
    cameraParameters?: any;
  };
}) => {
  const { src } = props;
  let needDrawRect: any = [];
  let originW = 0;
  let originH = 0;
  const imgRef: any = useRef(null);
  const cvRef: any = useRef(null);
  function initCanvas() {
    if (!imgRef.current) {
      return;
    }
    const img = imgRef.current.children[0].children[0];
    const cv = cvRef.current;
    const w = img.width;
    const h = img.height;
    cv.style.width = w + 'px';
    cv.style.height = h + 'px';
    // cv.width = w;
    // cv.height = h;
  }

  function get_lidar_corners(center: THREE.Vector3, l: number, w: number, h: number, yaw: number) {
    // cam_left_front测试数据
    //   center = new THREE.Vector3(81.76316, -17.274519, 1.3898289)
    //   yaw = 0.0012265434732495987
    //   l = 0.7407482697121843
    //   w = 0.8145941373349428
    //   h = 1.7
    // 基于物体自身建立坐标系，物体中心为坐标系中心，8个点的坐标为
    const arr = [
      [1, 1, 1],
      [1, -1, 1],
      [1, -1, -1],
      [1, 1, -1],
      [-1, 1, 1],
      [-1, -1, 1],
      [-1, -1, -1],
      [-1, 1, -1],
    ];
    const r = new THREE.Matrix4().makeRotationZ(yaw);
    const vPoints = arr.map((item) => {
      return new THREE.Vector3((l / 2) * item[0], (w / 2) * item[1], (h / 2) * item[2])
        .applyMatrix4(r)
        .add(center);
    });
    return vPoints;
  }
  function tran_lidar2cam(lidar_points: any[], cam2liar_r_params: any, cam2lidar_t: THREE.Vector3) {
    // 传入一个目标的8个点的世界坐标[[], [], []]， 相机转世界的RT,
    // 返回的目标8个点的相机坐标
    // const lidar2cam_r = cam2liar_r.invert();
    const cam2liar_r = cam2liar_r_params.clone().invert();
    const res = lidar_points.map((item) => {
      return item.sub(cam2lidar_t).applyMatrix3(cam2liar_r);
    });
    return res;
  }
  function getUV(params: string | any[], cam_k: any, imageW: any, imageH: any) {
    const min = new THREE.Vector3(0, 0, 0);
    const max = new THREE.Vector3(imageW, imageH, 1);
    const res = [];
    for (let i = 0; i < params.length; i++) {
      const ele = params[i];
      if (ele.z < 0) {
        return [];
      }
      ele.applyMatrix3(cam_k).divideScalar(ele.z).clamp(min, max);
      res.push(ele);
    }
    return res;
  }

  function draw() {
    if (!props.data) {
      return;
    }
    const allRect = props?.allRect;
    // console.log(props)
    const cam_back = props.data?.cameraParameters;
    const imageW = cam_back.image.width;
    const imageH = cam_back.image.height;
    const r: any = new THREE.Matrix3();
    r.set(...cam_back.extrinsic.r.split(',').map((item: string) => parseFloat(item)));
    const t = new THREE.Vector3(
      ...cam_back.extrinsic.t.split(',').map((item: string) => parseFloat(item)),
    );
    const k: any = new THREE.Matrix3();
    k.set(...cam_back.intrinsic.k.split(',').map((item: string) => parseFloat(item)));
    const finalXZY: any = [];
    allRect.forEach((item: { id: any; meta: { geometry: any } }) => {
      const v = item.meta.geometry;
      const center = new THREE.Vector3(v.positionX, v.positionY, v.positionZ);
      const one = get_lidar_corners(center, v.length, v.width, v.height, v.yaw);
      const oneInLidar = tran_lidar2cam(one, r, t);
      const uv = getUV(oneInLidar, k, imageW, imageH);
      if (uv.length > 0) {
        finalXZY.push(uv);
        needDrawRect.push({ id: item.id, index: needDrawRect.length });
      }
    });
    function drawRect() {
      let canvasEle = cvRef.current;
      let ctx = canvasEle.getContext('2d');
      canvasEle.width = imageW;
      canvasEle.height = imageH;
      finalXZY.forEach((item: any, index: any) => {
        ctx.beginPath();
        ctx.moveTo(item[0].x, item[0].y);
        ctx.lineTo(item[1].x, item[1].y);
        ctx.lineTo(item[2].x, item[2].y);
        ctx.lineTo(item[3].x, item[3].y);
        ctx.lineTo(item[0].x, item[0].y);
        ctx.lineWidth = 6;
        ctx.strokeStyle = 'blue';
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(item[0].x, item[0].y);
        ctx.lineTo(item[4].x, item[4].y);
        ctx.lineTo(item[5].x, item[5].y);
        ctx.lineTo(item[6].x, item[6].y);
        ctx.lineTo(item[7].x, item[7].y);
        ctx.lineTo(item[4].x, item[4].y);
        ctx.moveTo(item[1].x, item[1].y);
        ctx.lineTo(item[5].x, item[5].y);
        ctx.moveTo(item[2].x, item[2].y);
        ctx.lineTo(item[6].x, item[6].y);
        ctx.moveTo(item[3].x, item[3].y);
        ctx.lineTo(item[7].x, item[7].y);
        ctx.lineWidth = 6;
        ctx.strokeStyle = 'green';
        if (props.sel === needDrawRect[index].id) {
          ctx.strokeStyle = 'red';
        }
        ctx.stroke();
      });
    }
    drawRect();
  }
  window.addEventListener('resize', function () {
    initCanvas();
    draw();
  });
  useEffect(() => {
    initCanvas();
    draw();
  }, [props]);

  // function onTransform() {
  //   const cv = cvRef.current;
  //   console.log(imgRef.current.childNodes[2].childNodes[1].childNodes[0].childNodes[1].childNodes[0].childNodes[0].childNodes[0])
  //   const pre = imgRef.current.childNodes[2].childNodes[1].childNodes[0].childNodes[1].childNodes[0].childNodes[0].childNodes[0]
  //   console.log(pre.offsetWidth, pre.style.transform);
  //   console.log(cv.style)
  //   // cv.style.transform = pre.style.transform
  //     console.log(pre)
  //     // setTimeout(() => {

  //     //   const w = pre.offsetWidth;
  //     //   const h = pre.offsetHeight;
  //     //   console.log(w, h)
  //     //   cv.style.zIndex = 1200;
  //     //   cv.style.width = w + 'px';
  //     //   cv.style.height = h + 'px';
  //     //   cv.style.position = 'fixed';
  //     // }, 0);
  // }
  function onVisibleChange(val: any) {
    let pre: any = document.querySelectorAll(`[src="${src}"]`);
    pre = pre[1];
    const cv = cvRef.current;
    if (val) {
      setTimeout(() => {
        const w = pre.offsetWidth;
        const h = pre.offsetHeight;
        originW = cv.offsetWidth;
        originH = cv.offsetHeight;
        cv.style.zIndex = 1200;
        cv.style.width = w + 'px';
        cv.style.height = h + 'px';
        cv.style.position = 'fixed';
      }, 0);
    } else {
      cv.style.zIndex = 'auto';
      cv.style.width = originW + 'px';
      cv.style.height = originH + 'px';
      cv.style.position = 'absolute';
    }
  }

  return (
    <div ref={imgRef} style={{ width: '100%', height: '100%', position: 'relative' }}>
      <Image
        // id={"jjkktt"}
        src={src}
        rootClassName="shiImage"
        preview={{
          scaleStep: 0,
          onVisibleChange,
          // onTransform:onTransform,
          // getContainer: imgRef.current,
          // forceRender: true,
          toolbarRender: () => {
            return <></>;
          },
        }}
        // preview={false} // 防止点击预览
        // alt="Your Image Alt Text"
        style={{ width: '100%', height: '100%' }}
      />
      <canvas
        ref={cvRef}
        style={{
          position: 'absolute',
          left: '50%',
          top: '50%',
          translate: '-50% -50%',
          pointerEvents: 'none',
          transition: 'all 0.3s 0s',
        }}
      ></canvas>
    </div>
  );
};

export default TargetDetection;
